﻿using SearchInFiles.Windows;
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;

namespace SearchInFiles
{
    static class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            AssemblyLoadContext.Default.Resolving += ResolveAssembly;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            App app = new App();
            app.InitializeComponent();
            MainWindow window = new MainWindow();
            app.Run(window);
        }

        private static Assembly ResolveAssembly(AssemblyLoadContext assemblyLoadContext, AssemblyName assemblyName)
        {
            var probeSetting = AppContext.GetData("SubdirectoriesToProbe") as string;
            if (string.IsNullOrEmpty(probeSetting))
            {
                return null!;
            }

            foreach (var subDirectory in probeSetting.Split(';'))
            {
                var pathMaybe = System.IO.Path.Combine(AppContext.BaseDirectory, subDirectory, $"{assemblyName.Name}.dll");
                if (File.Exists(pathMaybe))
                {
                    return assemblyLoadContext.LoadFromAssemblyPath(pathMaybe);
                }
            }

            return null!;
        }
    }
}
